import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/model/user_model.dart';
import 'package:flutter_learn_vi/src/page/common/user_protocol_page.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/sp_utils.dart';
import 'package:flutter_learn_vi/src/welcome_page.dart';
import 'package:mobpush_plugin/mobpush_plugin.dart';

import 'base/pop_base_state.dart';
import 'bean/bean_app_setting.dart';
import 'bean/bean_setting.dart';
import 'bean/bean_user.dart';
import 'common/application.dart';
import 'common/sp_key.dart';
import 'common/user_helper.dart';
import 'net/dio_utils.dart';
import 'utils/log_util.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/7/20.
///
/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/9/25.
///
/// gongzhonghao biglead
/// https://study.163.com/instructor/1021406098.htm
/// https://blog.csdn.net/zl18603543572
/// https://www.toutiao.com/c/user/token/MS4wLjABAAAAYMrKikomuQJ4d-cPaeBqtAK2cQY697Pv9xIyyDhtwIM/

///lib/src/index_page.dart
///启动页面
class IndexPage extends StatefulWidget {
  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends PopBaseState<IndexPage> with UserModel {
  ///用户是否第一次使用
  bool _userFirst = false;

  @override
  void initState() {
    super.initState();
    //Widget渲染完成的回调
    // WidgetsBinding.instance.addPostFrameCallback((_) {
    //   //检查权限
    //   checkPermissonFunction();
    // });
    Future.delayed(Duration.zero, () {
      //检查权限
      checkPermissonFunction();
    });
  }

  ///lib/app/index_page.dart
  ///常用的第三方的初始功能 如友盟统计
  ///获取保存的用户偏好设置
  void initData() async {
    //App类型
    Application.getInstance.initApplication(Application.APP_KUANG_DENG);
    //获取当前的运行环境
    //当App运行在Release环境时，inProduction为true；
    //当App运行在Debug和Profile环境时，inProduction为false。
    const bool inProduction = const bool.fromEnvironment("dart.vm.product");
    //为ture时输出日志
    bool isLog = !inProduction;
    //初始化友盟统计
    // await initUmeng(isLog: isLog);
    //初始化本地存储工具
    await SPUtil.init();

    //初始化日志工具
    LogUtils.init(tag: "flutter_log", isDebug: isLog);

    //获取用户是否第一次登录
    _userFirst = await SPUtil.getBool(spUserIsFirstKey);

    // //获取用户隐私协议的状态
    // bool _userProtocol = await SPUtil.getBool(spUserProtocolKey);
    //
    // //记录
    // UserHelper.getInstance.userProtocol = _userProtocol;
    //初始化用户的登录信息
    UserHelper.getInstance.init();
    //下一步
    openUserProtocol();
  }

  ///lib/app/index_page.dart
  ///构建[IndexPage]中的友盟统计
  Future<bool> initUmeng({bool isLog = false}) async {
    /// 监听原生消息
    // FlutterFaiUmeng.receiveMessage((message) {
    //   LogUtils.e(message.toString());
    // });
    //
    // ///友盟的初始化
    // ///参数一 appkey
    // ///参数二 推送使用的pushSecret
    // ///参数三 是否打开调试日志
    // await FlutterFaiUmeng.uMengInit("5dcfb8f84ca357f70e000b0a",
    //     pushSecret: "5cb4fc014c143a77fb85cb17edd807a2", logEnabled: isLog);
    return Future.value(true);
  }

  ///lib/app/index_page.dart
  ///构建[IndexPage]中的显示内容
  @override
  Widget build(BuildContext context) {
    return Scaffold(

      ///层叠布局
      body: Stack(
        children: [

          ///构建背景
          Positioned(
            left: 0,
            right: 0,
            top: 0,
            bottom: 0,
            child: CupertinoActivityIndicator(),
          ),
        ],
      ),
    );
  }

  ///lib/app/index_page.dart
  ///构建[IndexPage]中的异步的
  ///权限请求判断
  void checkPermissonFunction() {
    ///权限请求结束获取权限后进行初始化操作
    ///如果未获取权限是对权限进行关闭的
    initData();
  }

  ///lib/app/index_page.dart
  ///判断用户隐私协议
  void openUserProtocol() {
    //已同意用户隐私协议 下一步
    if (UserHelper.getInstance.isUserProtocol) {
      openNext();
    } else {
      //未同意用户协议 弹框显示
      showUserProtocolPage(
        context: context,
        dismissCallback: (value) {
          UserHelper.getInstance.userProtocol = true;
          //设置隐私协议授权状态
          MobpushPlugin.updatePrivacyPermissionStatus(true);
          openNext();
        },
      );
    }
  }

  ///进入首页面或者是引导页面
  void openNext() async {
    //设置远程推送环境，向用户授权（仅 iOS)
    if (Platform.isIOS) {
      MobpushPlugin.setCustomNotification();
    }
    if (Platform.isIOS) {
      //设置远程推送环境 (仅 iOS)：
      // 开发环境 false, 线上环境 true
      MobpushPlugin.setAPNsForProduction(HttpHelper.isDebug);
    }

    Map<String, dynamic> map = {};
    ResponseInfo partResponseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.appdetection,
      queryParameters: map,
    );
    if (partResponseInfo.success) {
      Map element = partResponseInfo.data;
      SettingBean settingBean = SettingBean.fromJson(element);
      UserHelper.getInstance.settingBean = settingBean;
    }

    await getUserInfo();

    UserBean userBean = UserHelper.getInstance.userBean;

    if (userBean != null) {
      bool result = await checkUserInfo(userBean.userId);
      if (!result) {
        userBean = null;
        UserHelper.getInstance.setUserBean(null);
      }
    }
    if (userBean != null &&
        (UserHelper.getInstance.startUrlList == null ||
            UserHelper.getInstance.startUrlList.length == 0)) {
      Map<String, dynamic> map = {};

      ResponseInfo partResponseInfo = await DioUtils.instance.getRequest(
        url: HttpHelper.bootpage,
        queryParameters: map,
      );
      if (partResponseInfo.success) {
        List requestList = partResponseInfo.data;
        List<String> startUrlList = [];
        requestList.forEach((element) {
          startUrlList.add(element.toString());
        });
        UserHelper.getInstance.startUrlList = startUrlList;
      }
    }

    Map<String, dynamic> map2 = {};
    if (userBean != null) {
      map2["mineId"] = userBean.mineId;
    }
    //网络请求获取APP的配置信息
    ResponseInfo responseInfo = await DioUtils.instance
        .getRequest(url: HttpHelper.SETTING_URL, queryParameters: map2);
    if (responseInfo.success) {
      //解析数据
      AppSettingBean settingBean = AppSettingBean.fromMap(responseInfo.data);
      UserHelper.getInstance.appSettingBean = settingBean;
    }
    if (mounted) {
      NavigatorUtils.openPageByFade(context, WelcomePage(), isReplace: true);
    }
    //获取配置信息
    // if (_userFirst == null || _userFirst == false) {
    //   ///第一次 隐藏logo 显示左右滑动的引导
    //   NavigatorUtils.openPageByFade(context, SplashPage(), isReplace: true);
    // } else {
    //   ///非第一次 隐藏logo 显示欢迎
    //   NavigatorUtils.openPageByFade(context, WelcomePage(), isReplace: true);
    // }
  }
}
